<template>
    <el-drawer v-model="drawerVisible" :destroy-on-close="true" size="500px" :title="`${drawerProps.title}工位`">
        <el-form ref="ruleFormRef" label-width="120px" label-suffix=" :" :rules="rules" :disabled="drawerProps.isView"
            :model="drawerProps.row" :hide-required-asterisk="drawerProps.isView">
            <el-form-item label="工位编码" prop="workstationCode" v-if="drawerProps.title === '新增'">
                <el-input v-model="drawerProps.row.workstationCode" placeholder="请输入唯一工位编码" clearable maxlength="50" show-word-limit />
            </el-form-item>

            <el-form-item label="工位名称" prop="workstationName">
                <el-input v-model="drawerProps.row.workstationName" placeholder="请输入工位名称" clearable maxlength="100" show-word-limit />
            </el-form-item>

            <el-form-item label="所属产线" prop="productionLineId">
                <el-select v-model="drawerProps.row.productionLineId" placeholder="请选择产线" clearable style="width: 100%" @change="handleProductionLineChange">
                    <el-option v-for="line in productionLineList" :key="line.id" :label="`${line.factoryName}-${line.workshopName}-${line.lineName}`" :value="line.id" />
                </el-select>
            </el-form-item>

            <el-form-item label="所属工厂" prop="factoryName" v-if="selectedProductionLine || drawerProps.isView">
                <el-input v-model="displayFactoryName" disabled style="width: 100%" />
            </el-form-item>

            <el-form-item label="所属车间" prop="workshopName" v-if="selectedProductionLine || drawerProps.isView">
                <el-input v-model="displayWorkshopName" disabled style="width: 100%" />
            </el-form-item>

            <el-form-item label="工位类型" prop="workstationType">
                <el-select v-model="drawerProps.row.workstationType" placeholder="请选择工位类型" clearable style="width: 100%">
                    <el-option label="手动" value="MANUAL" />
                    <el-option label="自动" value="AUTOMATIC" />
                    <el-option label="半自动" value="SEMI_AUTOMATIC" />
                </el-select>
            </el-form-item>

            <el-form-item label="工位状态" prop="status">
                <el-select v-model="drawerProps.row.status" placeholder="请选择状态" clearable style="width: 100%">
                    <el-option label="空闲" value="IDLE" />
                    <el-option label="运行中" value="RUNNING" />
                    <el-option label="故障" value="FAULT" />
                    <el-option label="维护中" value="MAINTENANCE" />
                </el-select>
            </el-form-item>

            <el-form-item label="产能/小时" prop="capacity">
                <el-input-number v-model="drawerProps.row.capacity" :min="1" :max="9999" placeholder="请输入每小时产能" style="width: 100%" />
            </el-form-item>

            <el-form-item label="位置序号" prop="position">
                <el-input-number v-model="drawerProps.row.position" :min="1" :max="999" placeholder="请输入在产线中的位置序号" style="width: 100%" />
            </el-form-item>

            <el-form-item label="位置" prop="location" v-if="drawerProps.isView">
                <el-input v-model="drawerProps.row.location" disabled style="width: 100%" />
            </el-form-item>

            <el-form-item label="支持工艺类型" prop="supportedProcessTypes">
                <el-input v-model="drawerProps.row.supportedProcessTypes" type="textarea" :rows="2" placeholder="请输入支持的工艺类型，多个类型用逗号分隔，如：焊接,组装,测试" clearable maxlength="500" show-word-limit />
            </el-form-item>

            <el-form-item label="描述" prop="description">
                <el-input v-model="drawerProps.row.description" type="textarea" :rows="3" placeholder="请输入工位描述" clearable maxlength="500" show-word-limit />
            </el-form-item>
        </el-form>
        <template #footer>
            <el-button @click="drawerVisible = false">取消</el-button>
            <el-button v-show="!drawerProps.isView" type="primary" @click="handleSubmit">确定</el-button>
        </template>
    </el-drawer>
</template>

<script setup lang="ts" name="WorkstationDrawer">
import { ref, reactive, watch, computed } from "vue";
import { ElMessage, type FormInstance } from "element-plus";
import type { Workstation } from "@/api/modules/workstation";
import { getEnabledProductionLineList } from "@/api/modules/workstation";

// 抽屉属性接口
interface DrawerProps {
    title: string;
    isView: boolean;
    row: Partial<Workstation.WorkstationListItem>;
    api?: (params: any) => Promise<any>;
    getTableList?: () => void;
}

// 产线数据
const productionLineList = ref<{ id: string; lineName: string; factoryName: string; workshopName: string }[]>([]);
const selectedProductionLine = ref<{ factoryName: string; workshopName: string } | null>(null);

// 表单验证规则
const rules = reactive({
    workstationCode: [
        { required: true, message: "工位编码不能为空" },
        { max: 50, message: "长度不能超过50个字符" }
    ],
    workstationName: [
        { required: true, message: "工位名称不能为空" },
        { max: 100, message: "长度不能超过100个字符" }
    ],
    productionLineId: [
        { required: true, message: "请选择所属产线" }
    ],
    workstationType: [
        { required: true, message: "请选择工位类型" }
    ],
    supportedProcessTypes: [
        { max: 500, message: "长度不能超过500个字符" }
    ],
    description: [
        { max: 500, message: "长度不能超过500个字符" }
    ]
});

// 抽屉可见性
const drawerVisible = ref(false);

// 抽屉属性
const drawerProps = ref<DrawerProps>({
    isView: false,
    title: "",
    row: {}
});

// 表单引用
const ruleFormRef = ref<FormInstance>();

// 计算属性：显示的工厂名称
const displayFactoryName = computed(() => {
    if (selectedProductionLine.value) {
        return selectedProductionLine.value.factoryName;
    }
    // 查看模式下，从工位数据中获取
    if (drawerProps.value.isView && drawerProps.value.row.factoryName) {
        return drawerProps.value.row.factoryName;
    }
    return '';
});

// 计算属性：显示的车间名称
const displayWorkshopName = computed(() => {
    if (selectedProductionLine.value) {
        return selectedProductionLine.value.workshopName;
    }
    // 查看模式下，从工位数据中获取
    if (drawerProps.value.isView && drawerProps.value.row.workshopName) {
        return drawerProps.value.row.workshopName;
    }
    return '';
});

// 产线选择变化处理
const handleProductionLineChange = (productionLineId: string) => {
    if (productionLineId) {
        const selectedLine = productionLineList.value.find(line => line.id === productionLineId);
        if (selectedLine) {
            selectedProductionLine.value = {
                factoryName: selectedLine.factoryName,
                workshopName: selectedLine.workshopName
            };
        }
    } else {
        selectedProductionLine.value = null;
    }
};

// 获取产线列表
const loadProductionLineList = async () => {
    try {
        const res = await getEnabledProductionLineList();
        productionLineList.value = res.data || [];
        
        // 如果是编辑模式且已有产线ID，设置选中的产线信息
        if (drawerProps.value.row.productionLineId) {
            handleProductionLineChange(drawerProps.value.row.productionLineId);
        }
    } catch (error) {
        console.error('获取产线列表失败:', error);
    }
};

// 监听抽屉打开状态
watch(drawerVisible, (visible) => {
    if (visible) {
        loadProductionLineList();
        // 设置默认状态
        if (drawerProps.value.title === '新增' && !drawerProps.value.row.status) {
            drawerProps.value.row.status = 'IDLE';
        }
    } else {
        // 关闭时清空选中的产线信息
        selectedProductionLine.value = null;
    }
});

// 接收父组件传过来的参数
const acceptParams = (params: DrawerProps) => {
    drawerProps.value = params;
    drawerVisible.value = true;
};

// 提交数据（新增/编辑）
const handleSubmit = () => {
    ruleFormRef.value?.validate(async valid => {
        if (!valid) return;
        try {
            console.log("drawerProps.value.row",drawerProps.value.row)
            await drawerProps.value.api?.(drawerProps.value.row);
            ElMessage.success({ message: `${drawerProps.value.title}工位成功！` });
            drawerProps.value.getTableList?.();
            drawerVisible.value = false;
        } catch (error) {
            console.error(error);
        }
    });
};

// 暴露方法给父组件
defineExpose({
    acceptParams
});
</script>

<style scoped>
.el-drawer__body {
    padding: 20px;
}
</style>